package com.dream.inspect.modules.business.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.dream.inspect.common.utils.DateFormatUtil;
import com.dream.inspect.common.utils.DateUtils;
import com.dream.inspect.common.utils.PageUtils;
import com.dream.inspect.common.utils.Query;
import com.dream.inspect.modules.business.dao.SuperviseProjectDao;
import com.dream.inspect.modules.business.entity.SuperviseProjectEntity;
import com.dream.inspect.modules.business.service.SuperviseProjectService;
import com.dream.inspect.modules.dream.pojo.SuperviseProjectFormMap;


@Service("superviseProjectService")
public class SuperviseProjectServiceImpl extends ServiceImpl<SuperviseProjectDao, SuperviseProjectEntity> implements SuperviseProjectService {

	@Resource
	private SuperviseProjectDao superviseProjectDao;
	

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<SuperviseProjectEntity> page = this.selectPage(
                new Query<SuperviseProjectEntity>(params).getPage(),
                new EntityWrapper<SuperviseProjectEntity>()
        );

        return new PageUtils(page);
    }

	@Override
	public PageUtils findProjectList(Map<String, Object> params) {
		Page<SuperviseProjectFormMap> page = selectThisPage(new Query<SuperviseProjectFormMap>(params),
				new Query<SuperviseProjectFormMap>(params).getPage()
		);

		return new PageUtils(page);
	}

	private Page<SuperviseProjectFormMap> selectThisPage(Map<String ,Object> map, Page<SuperviseProjectFormMap> page) {
		page.setRecords(superviseProjectDao.findProjectList(map,page));
		return page;
	}
	@Override
	public List<SuperviseProjectEntity> findAllList(Map<String, String> params) {
    	int currPage = Integer.valueOf(params.get("currPage"));
    	int pageSize  = Integer.valueOf(params.get("pageSize"));
    	currPage = (currPage - 1) * pageSize;
		
		String sortByTime = params.get("sortByTime");//时间排序（1：升序，2：降序）
		//拼接条件
        EntityWrapper<SuperviseProjectEntity> wrapper = addCondition(params);
		
		//时间排序（1：升序，2：降序）
    	if (StringUtils.isNotEmpty(sortByTime)) {
    		if ("1".equals(sortByTime)) {
    			wrapper.orderBy("sp.CREATE_TIME", true);
    		} else {
    			wrapper.orderBy("sp.CREATE_TIME", false);
    		}
    	}
		
		List<SuperviseProjectEntity> dataList = new ArrayList<SuperviseProjectEntity>();
		dataList = baseMapper.findAllList(wrapper, currPage, pageSize);
        return dataList;
	}

	@Override
	public SuperviseProjectEntity findDetailInfo(Map<String, String> params) {

		SuperviseProjectEntity spEntity = new SuperviseProjectEntity();
		String id = params.get("id");
		if (StringUtils.isNotEmpty(id)) {
			spEntity.setId(Long.valueOf(id));
			
			EntityWrapper<SuperviseProjectEntity> wrapper=new EntityWrapper<SuperviseProjectEntity>();
			wrapper.setEntity(new SuperviseProjectEntity());
			wrapper.eq("sp.id", id);
			spEntity = baseMapper.findDetailInfo(wrapper);
		}
		
		return spEntity;
	}

	@Override
	public int findAllListCount(Map<String, String> params) {
		//查询条件
        EntityWrapper<SuperviseProjectEntity> wrapper = addCondition(params);

        int countNum = baseMapper.findAllListCount(wrapper);
        return countNum;
	}
	
	@Override
	public Long insertSuperviseProject(Map<String, String> params) {
		Long result = 0L;
        Date now = new Date();
        String userId = params.get("userId");
        String modelId = params.get("modelId");
        String titleName = params.get("titleName");
        String zbdwId = params.get("zbdwId");
        String jzrq = params.get("jzrq");
        String startTime = params.get("startTime");
        String description = params.get("description");
        String lxrq = params.get("lxrq");
        String projectStatus = params.get("projectStatus");
        String dcssfs = params.get("dcssfs");
        String sflhdc = params.get("sflhdc");
        String msgFlag = params.get("msgFlag");
        String projectJsonInfo = params.get("projectJsonInfo");
        String dclx = params.get("dclx");
        String filePath = params.get("filePath");
        String fileName = params.get("fileName");

        SuperviseProjectEntity spEntity = new SuperviseProjectEntity();
        if (StringUtils.isNotEmpty(modelId)) {
        	spEntity.setModelId(Long.valueOf(modelId));                                  //督察模板id
        }
        if (StringUtils.isNotEmpty(filePath)) {
        	spEntity.setFilePath(filePath);                                  //路径
        }
        if (StringUtils.isNotEmpty(fileName)) {
        	spEntity.setFileName(fileName);                                  //名称
        }
        if (StringUtils.isNotEmpty(titleName)) {
        	spEntity.setTitleName(titleName);                                            //专项名称
        }
        if (StringUtils.isNotEmpty(zbdwId)) {
        	spEntity.setZbdwId(Long.valueOf(zbdwId));                                    //主办单位id
        }
        if (StringUtils.isNotEmpty(jzrq)) {
        	spEntity.setJzrq(DateUtils.stringToDate(jzrq, DateUtils.DATE_TIME_PATTERN)); //截止日期
        }
        if (StringUtils.isNotEmpty(startTime)) {
        	spEntity.setStartTime(DateUtils.stringToDate(startTime, DateUtils.DATE_TIME_PATTERN)); //开始日期
        }
        if (StringUtils.isNotEmpty(description)) {
        	spEntity.setDescription(description);                                        //督察描述
        }
        if (StringUtils.isNotEmpty(lxrq)) {
        	spEntity.setLxrq(DateUtils.stringToDate(lxrq, DateUtils.DATE_PATTERN));      //立项日期
        }
        if (StringUtils.isNotEmpty(projectStatus)) {
        	spEntity.setProjectStatus(projectStatus);           //项目状态(0：立项中，1：进行中，2：办结中，3：已办结)         
        }
        if (StringUtils.isNotEmpty(dcssfs)) {
        	spEntity.setDcssfs(dcssfs);                        //督察实施方式(0：明察，1：暗访)
        }
        if (StringUtils.isNotEmpty(sflhdc)) {
        	spEntity.setSflhdc(sflhdc);                        //是否联合督察(0：否，1：是)
        }
        if (StringUtils.isNotEmpty(msgFlag)) {
        	spEntity.setMsgFlag(msgFlag);                       //是否短信通知(0：通知，1：不通知)
        }
        if (StringUtils.isNotEmpty(projectJsonInfo)) {
        	spEntity.setProjectJsonInfo(projectJsonInfo);       //专项JSON信息
        }
		if (StringUtils.isNotEmpty(dclx)) {
			spEntity.setDclx(dclx);       //专项类型
		}
        spEntity.setCreateUser(Long.valueOf(userId));           //创建人id
        spEntity.setCreateTime(now);                            //创建时间
        spEntity.setUpdateUser(Long.valueOf(userId));           //更新人id
        spEntity.setUpdateTime(now);                            //更新时间
        
        //save
        this.insert(spEntity);
        
        result = spEntity.getId();
        return result;
	}
	
	@Override
	public boolean updateSuperviseProject(Map<String, String> params) {
		
		boolean result = false;
        Date now = new Date();
        String projectId = params.get("id");
        String userId = params.get("userId");
        String projectStatus = params.get("projectStatus");
        String deleteFlag = params.get("deleteFlag");
        String lxspzt  = params.get("lxspzt");
		String modelId = params.get("modelId");
		String titleName = params.get("titleName");
		String zbdwId = params.get("zbdwId");
		String jzrq = params.get("jzrq");
		String startTime = params.get("startTime");
		String description = params.get("description");
		String lxrq = params.get("lxrq");
		String dcssfs = params.get("dcssfs");
		String sflhdc = params.get("sflhdc");
		String msgFlag = params.get("msgFlag");
		String projectJsonInfo = params.get("projectJsonInfo");
		String dclx = params.get("dclx");
		String filePath = params.get("filePath");
		String fileName = params.get("fileName");

        SuperviseProjectEntity spEntity = new SuperviseProjectEntity();
		if (StringUtils.isNotEmpty(filePath)) {
			spEntity.setFilePath(filePath);                                  //路径
		}
		if (StringUtils.isNotEmpty(fileName)) {
			spEntity.setFileName(fileName);                                  //名称
		}
        if (StringUtils.isNotEmpty(projectId)) {
        	spEntity.setId(Long.valueOf(projectId));            //专项id
        }
        if (StringUtils.isNotEmpty(lxspzt)) {
        	spEntity.setLxspzt(lxspzt);                         //立项审批状态(0：立项待审核，1：立项审核未通过，2：立项审核通过，3：办结待审核，4：办结审核未通过，5：办结审核通过)
        	spEntity.setLxspsj(now);
        	spEntity.setLxspr(Long.valueOf(userId));
        }
		if (StringUtils.isNotEmpty(modelId)) {
			spEntity.setModelId(Long.valueOf(modelId));                                  //督察模板id
		}
		if (StringUtils.isNotEmpty(titleName)) {
			spEntity.setTitleName(titleName);                                            //专项名称
		}
		if (StringUtils.isNotEmpty(zbdwId)) {
			spEntity.setZbdwId(Long.valueOf(zbdwId));                                    //主办单位id
		}
		if (StringUtils.isNotEmpty(jzrq)) {
			spEntity.setJzrq(DateUtils.stringToDate(jzrq, DateUtils.DATE_TIME_PATTERN)); //截止日期
		}
		if (StringUtils.isNotEmpty(startTime)) {
			spEntity.setStartTime(DateUtils.stringToDate(startTime, DateUtils.DATE_TIME_PATTERN)); //开始日期
		}
		if (StringUtils.isNotEmpty(description)) {
			spEntity.setDescription(description);                                        //督察描述
		}
		if (StringUtils.isNotEmpty(lxrq)) {
			spEntity.setLxrq(DateUtils.stringToDate(lxrq, DateUtils.DATE_PATTERN));      //立项日期
		}
		if (StringUtils.isNotEmpty(dcssfs)) {
			spEntity.setDcssfs(dcssfs);                        //督察实施方式(0：明察，1：暗访)
		}
		if (StringUtils.isNotEmpty(sflhdc)) {
			spEntity.setSflhdc(sflhdc);                        //是否联合督察(0：否，1：是)
		}
		if (StringUtils.isNotEmpty(msgFlag)) {
			spEntity.setMsgFlag(msgFlag);                       //是否短信通知(0：通知，1：不通知)
		}
		if (StringUtils.isNotEmpty(projectJsonInfo)) {
			spEntity.setProjectJsonInfo(projectJsonInfo);       //专项JSON信息
		}
		if (StringUtils.isNotEmpty(dclx)) {
			spEntity.setDclx(dclx);       //专项类型
		}
        //项目状态(0：立项中，1：进行中，2：办结中，3：取消办结，4：已办结)
        if (StringUtils.isNotEmpty(projectStatus)) {             
        	spEntity.setProjectStatus(projectStatus);                      
        }
        if (StringUtils.isNotEmpty(deleteFlag)) {
        	spEntity.setDeleteFlag(deleteFlag);                 //删除标志(0：未删除，1：已删除)
        }
        spEntity.setUpdateUser(Long.valueOf(userId));           //更新人id
        spEntity.setUpdateTime(now);                            //更新时间
        
        //save
        result = this.updateById(spEntity);
        
        return result;
	}
	
	@Override
	public SuperviseProjectEntity findSuperviseProjectById(Map<String, String> params) {

        String id = params.get("id");
        //查询条件
        EntityWrapper<SuperviseProjectEntity> wrapper=new EntityWrapper<SuperviseProjectEntity>();
		wrapper.setEntity(new SuperviseProjectEntity());
		if (StringUtils.isNotEmpty(id)) {
			wrapper.eq("sp.id", id);            //专项id
        }
		
		SuperviseProjectEntity spEntity= baseMapper.findSuperviseProjectById(wrapper);

		Object s= JSON.parse(spEntity.getProjectJsonInfo());
		List<Map> map=(List<Map>)s;
		spEntity.setProjectMapList(map);
       return spEntity;
        
	}
	
	@Override
	public int selectThisMonthCount(Map<String, String> params) {
		//查询条件
        EntityWrapper<SuperviseProjectEntity> wrapper = addCondition(params);

        int countNum = baseMapper.selectThisMonthCount(wrapper);
        return countNum;
	}
	
	@Override
	public int findZczxAndLhdcCount(Map<String, String> params) {
		//查询条件
        EntityWrapper<SuperviseProjectEntity> wrapper = addCondition(params);

        int countNum = baseMapper.findZczxAndLhdcCount(wrapper);
        return countNum;
	}

	@Override
	public List<SuperviseProjectEntity> findZczxAndLhdcList(Map<String, String> params) {
		int currPage = Integer.valueOf(params.get("currPage"));
    	int pageSize  = Integer.valueOf(params.get("pageSize"));
    	currPage = (currPage - 1) * pageSize;
		
		String sortByTime = params.get("sortByTime");//时间排序（1：升序，2：降序）
		//拼接条件
        EntityWrapper<SuperviseProjectEntity> wrapper = addCondition(params);
		
		//时间排序（1：升序，2：降序）
    	if (StringUtils.isNotEmpty(sortByTime)) {
    		if ("1".equals(sortByTime)) {
    			wrapper.orderBy("sp.LXRQ", true);
    		} else {
    			wrapper.orderBy("sp.LXRQ", false);
    		}
    	}
		
		List<SuperviseProjectEntity> dataList = new ArrayList<SuperviseProjectEntity>();
		dataList = baseMapper.findZczxAndLhdcList(wrapper, currPage, pageSize);
        return dataList;
	}
	
	@Override
	public SuperviseProjectEntity findSuperviseProjectForCzztById(Map<String, String> params) {
		String id = params.get("id");
        //查询条件
        EntityWrapper<SuperviseProjectEntity> wrapper=new EntityWrapper<SuperviseProjectEntity>();
		wrapper.setEntity(new SuperviseProjectEntity());
		if (StringUtils.isNotEmpty(id)) {
			wrapper.eq("sp.id", id);            //专项id
        }
//		wrapper.groupBy("sp.id, sp.TITLE_NAME,sp.LXSPR");
		
		SuperviseProjectEntity spEntity= baseMapper.findSuperviseProjectForCzztById(wrapper);
        
       return spEntity;
	}
	
	@Override
	public SuperviseProjectEntity findSuperviseProjectForSearchPage(Map<String, String> params) {
		String id = params.get("id");
        return baseMapper.findSuperviseProjectForSearchPage(id);
	}

	@Override
	public int findSuperviseProjectForSearchPageCount(Map<String, String> params) {
		//查询条件
        EntityWrapper<SuperviseProjectEntity> wrapper = addCondition(params);

        int countNum = baseMapper.findSuperviseProjectForSearchPageCount(wrapper);
        return countNum;
	}
	
	@Override
	public List<SuperviseProjectEntity> findAllForSearchPage(Map<String, String> params) {
		int currPage = Integer.valueOf(params.get("currPage"));
        int pageSize  = Integer.valueOf(params.get("pageSize"));
        currPage = (currPage - 1) * pageSize;
        List<SuperviseProjectEntity> sqrList = new ArrayList<SuperviseProjectEntity>();
        //组装条件
        //EntityWrapper<SuperviseProjectEntity> wrapper = addCondition(params);
		String searchAllText = "";
		if(params.containsKey("searchText") && StringUtils.isNotEmpty(params.get("searchText"))){
			searchAllText = "%"+params.get("searchText") + "%";
		}
        String userDeptName = params.get("userDeptName");
        String deptId = params.get("deptId");
        String userId = params.get("userId");
        String flag = params.get("flag");
        sqrList = baseMapper.findAllForSearchPage(searchAllText, deptId, userId, userDeptName, flag,currPage, pageSize);
        return sqrList;
	}

	@Override
	public int findAllForSearchPageCount(Map<String, String> params) {
		//查询条件
        //EntityWrapper<SuperviseProjectEntity> wrapper = addCondition(params);
		String searchAllText = "";
		if(params.containsKey("searchText") && StringUtils.isNotEmpty(params.get("searchText"))){
			searchAllText = "%"+params.get("searchText") + "%";
		}

        String userDeptName = params.get("userDeptName");
        String deptId = params.get("deptId");
		String flag = params.get("flag");
        int countNum = baseMapper.findAllForSearchPageCount(searchAllText, deptId, userDeptName,flag);
        return countNum;
	}
	
	/**
	 * 拼接查询条件
	 * 
	 * @param params
	 * @return
	 */
	private EntityWrapper<SuperviseProjectEntity> addCondition(Map<String, String> params) {
    	String projectStatus = params.get("projectStatus");//专项状态0：立项中，1：进行中，2：办结中，3：已办结
    	String jzrqFlg = params.get("jzrqFlg");//截止日期标志
    	String userDwId = params.get("zbdwId");//用户所在单位ID
    	String spzt = params.get("spzt");//审批状态(0：待审核，1：审批未通过，2：已审批)
    	String userId = params.get("userId");//用户ID
    	String deptId = params.get("deptId");//部门ID
    	String thisMonthFlg = params.get("thisMonthFlg");//本月标志
    	String dclx = params.get("dclx");
    	String searchText = params.get("searchText");
    	String id = params.get("id");

		EntityWrapper<SuperviseProjectEntity> wrapper = new EntityWrapper<SuperviseProjectEntity>();
		wrapper.setEntity(new SuperviseProjectEntity());
	   
    	if (StringUtils.isNotEmpty(projectStatus)) {
    		wrapper.eq("sp.PROJECT_STATUS", projectStatus);
    	}
    	if (StringUtils.isNotEmpty(id)) {
    		wrapper.eq("sp.ID", id);
    	}
    	//0:未截止，1：已截止
		if (StringUtils.isNotEmpty(jzrqFlg)) {
			if ("1".equals(jzrqFlg)) {
				wrapper.and(" now() > sp.JZRQ ");
    		} else {
    			wrapper.and(" now() <= sp.JZRQ ");
    		}
		}
		if (StringUtils.isNotEmpty(spzt)) {
			wrapper.in("sp.LXSPZT", spzt);
//		} else {
//			wrapper.eq("sp.LXSPZT", "2");
		}
		if (StringUtils.isNotEmpty(userId)) {
			wrapper.eq("sp.CREATE_USER", userId);
		}
		if (StringUtils.isNotEmpty(deptId)) {
			wrapper.eq("sp.ZBDW_ID", deptId);
		}
		if (StringUtils.isNotEmpty(dclx)) {
    		wrapper.eq("sp.DCLX", dclx);
    	}
		wrapper.eq("sp.DELETE_FLAG", "0");
		if (StringUtils.isNotEmpty(thisMonthFlg)) {
			if ("1".equals(thisMonthFlg)) {
				String dt = DateFormatUtil.getFirstDayOfMonthForString();
				wrapper.and(" Date(sp.CREATE_TIME) >= '" + dt + "'");
			}
		}
		
		if (StringUtils.isNotEmpty(userDwId)) {
			wrapper.andNew();
   		 	wrapper.eq("sp.ZBDW_ID", userDwId);
            wrapper.or("st.TO_SSDW_ID={0}", userDwId);
		}
		
		//全文检索条件
		if (StringUtils.isNotEmpty(searchText)) {
			wrapper.andNew();
    		wrapper.like("sd.name", searchText);
    		wrapper.or("sp.TITLE_NAME like {0}", "%" + searchText + "%");
		}
		
    	return wrapper;
	}

}
